package org.demo.nio.reactor.multiplereactor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by tangwy on 2017/11/1.
 */
public class MainReactor implements Runnable {
    private Selector selector;
    private ServerSocketChannel ssc;
    private SelectorProvider selectorProvider;
    public MainReactor(int port) throws IOException {
        this(new InetSocketAddress(port));
    }

    public MainReactor(String ip, int port) throws IOException {
        this(new InetSocketAddress(ip,port));
    }

    public MainReactor(InetSocketAddress isa) throws IOException {
        this.selectorProvider=SelectorProvider.provider();
        ssc =selectorProvider.openServerSocketChannel(); //ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.socket().bind(isa);

        this.selector = selectorProvider.openSelector();
        ssc.register(selector, SelectionKey.OP_ACCEPT, new Acceptor(ssc,selectorProvider));
    }

    @Override
    public void run() {
        while (!Thread.interrupted()){
            try {
                selector.select(500);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    process(key);
                }
            } catch (IOException e) {
                //异常处理
                e.printStackTrace();
            }

        }
    }

    private void process(SelectionKey key) {
        Runnable r = (Runnable) key.attachment();
        //key.cancel();
        if(r!=null){
            r.run();
        }
    }
}
